//
//  MLNewsTableViewController.m
//  keJiNews
//
//  Created by 魔龙 on 16/4/16.
//  Copyright © 2016年 魔龙. All rights reserved.
//

#import "MLNewsTableViewController.h"
#import "MJRefresh.h"
#import "MLNews.h"
#import "MJExtension.h"
#import "MLNewsCell.h"
#import "MLDetailViewController.h"
#import "MLApiManager.h"

@interface MLNewsTableViewController ()

@property (nonatomic, strong) NSMutableArray *arrayList;
@property (nonatomic, assign) BOOL update;

@end

@implementation MLNewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadData];
    }];
    
    // 上拉加载更多数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMordData];
    }];
    
    // 进入tableView就刷新数据
    [self welcome];
    
    self.update = YES;
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(welcome) name:@"MLAdvertisementKey" object:nil];
}

// 隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)setUrlString:(NSString *)urlString{
    _urlString = urlString;
}

- (void)welcome{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"update"];
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"update"]) {
        return;
    }
    
    if (self.update == YES) {
        [self.tableView.mj_header beginRefreshing];
        self.update = NO;
    }
//    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"contentStart" object:nil]];
}

#pragma mark - 刷新数据
/**
 *  下拉刷新
 */
- (void)loadData{
    // http://c.m.163.com//nc/article/headline/T1348647853363/0-30.html
    NSString *allUrlString = [NSString stringWithFormat:@"/nc/article/%@/0-20.html",self.urlString];
   
    [self loadDataForType:1 withURL:allUrlString];
}

/**
 *  上拉加载更多数据
 */
- (void)loadMordData{
    NSString *allUrlString = [NSString stringWithFormat:@"/nc/article/%@/%ld-20.html",self.urlString,(self.arrayList.count - self.arrayList.count%10)];

    [self loadDataForType:2 withURL:allUrlString];
}

/**
 *   刷新数据公共方法
 */
- (void)loadDataForType:(int)type withURL:(NSString *)allUrlString{
    [[MLApiManager sharedApi] requestNewsDataWithURL:allUrlString success:^(NSDictionary *responseObject) {
                NSString *key = responseObject.keyEnumerator.nextObject;
                NSArray *tempArray = responseObject[key];
                NSArray *arrayM = [MLNews mj_objectArrayWithKeyValuesArray:tempArray];
                if (type == 1) { //下拉刷新
                    self.arrayList = [arrayM mutableCopy];
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView reloadData];
                } else if(type == 2){ //上拉加载
                    [self.arrayList addObjectsFromArray:arrayM];
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                }

    } error:^(NSError *errorInfo) {
         NSLog(@"%@",errorInfo);
    }];
}

#pragma mark - tableView数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MLNews *news = self.arrayList[indexPath.row];
    
    NSString *ID = [MLNewsCell idForRow:news];
    
    if((indexPath.row%20 == 0) && (indexPath.row != 0)){
        ID = @"NewsCell";
    }
    MLNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.news = news;
    return cell;
    
}

#pragma mark - tableView代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MLNews *news = self.arrayList[indexPath.row];
    
    CGFloat rowHeight = [MLNewsCell heightForRow:news];
    
    if ((indexPath.row%20 == 0)&&(indexPath.row != 0)) {
        rowHeight = 80;
    }
    
    return rowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出对应的模型
//    MLNews *news = self.arrayList[indexPath.row];
//    // 初始化详情页控制器
//    MLDetailViewController *detail = [[MLDetailViewController alloc] init];
//    detail.newsURL = news.fullURL;
//    if (detail.newsURL) {
//        // Push
//        [self.navigationController pushViewController:detail animated:YES];
//    }
    // 刚选中又马上取消选中，格子不变色
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self performSegueWithIdentifier:@"ShowDetailView" sender:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController isKindOfClass:[MLDetailViewController class]]) {
        
        
        MLNews *news = self.arrayList[self.tableView.indexPathForSelectedRow.row];
        MLDetailViewController *dc = segue.destinationViewController;
        dc.newsURL = news.fullURL;
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
    }else{
        NSLog(@"图片页");
//        MLNews *news = self.arrayList[self.tableView.indexPathForSelectedRow.row];
//        MLPhotoPage *photoPage = segue.destinationViewController;
//        photoPage.newsURL = news.fullURL;
    }
    
}

@end
